<template>
  <div
    v-if="isRefresh"
    class="stop-reason full-height bg-white page-content content relative-position"
  >
    <public-filter
      ref="publicFilter"
      v-model="queryParams"
      @setOprofNum="setOprofNum"
      ifBuildBox
      :init="selfParams"
      @onSearchData="selfParams"
    >
      <div class="form-inline" style="flex :0;padding-bottom: 14px">
        <q-btn
          class="btn"
          outline
          color="primary"
          :disable="!tableData.length"
          @click="downloadExcel"
          label="导出Excel"
        />
        <div class="flex-1"></div>
        <div class="flex items-center">
          <tips :tips="`${statusList[1].label}占比 = ${statusList[1].label}时长/当天班制内${statusList[1].label}与${statusList[0].label}时间X100%`" class="margin-r-10" />
          <q-toggle
            v-model="showScale"
            label="启用缩放"
            left-label
          />
        </div>
      </div>
    </public-filter>
    <!-- 原因切换 -->
    <div style="flex: 1;padding: 0 20px;" class="margin-b-20 scroll-box">
      <!-- 图表的标题 -->
      <div class="flex items-center justify-between" style="margin-top: 6px">
        <div class="flex items-center">
          <!-- <div>{{selLocation}}</div> -->
          <div>{{statusList[1].label}}原因分析（ {{oprof_start.date}}&nbsp;&nbsp;共{{oprof_start.num}}台设备）</div>
          <div style="width: 264px; height: 26px; margin-left:10px">
            <customized-switch
              :options="stopTypeOption"
              v-model="stopType"
              @change="onChangeStopType"
            />
          </div>
        </div>
      </div>
      <!-- echart 表 -->
      <div style="width: 100%; height: 400px" ref="dialogChart"></div>
      <!-- 显示的table -->
      <div class="padding-t-20">
        <q-table
          :data="tableData"
          :columns="[]"
          row-key="index"
          class="myTable my-sticky-header-table scroll stick-first-col no-margin"
          :hide-bottom="!!tableData.length"
          :pagination="{ rowsPerPage: 0 }"
          ref="reportTable"
          id="reportTable"
          :loading="tableLoading"
          color="primary"
        >
          <template v-slot:header>
            <q-tr>
              <q-th style="width: 100%">
                加工设备
              </q-th>
              <q-th style="padding: 0;width: 0" v-for="(item, index) in columns" :key="index">
                <div class="item border-bottom" :class="{'border-right': index !== columns.length - 1}">{{item.date || item.week || item.month}}</div>
                <div class="flex nowrap">
                  <template v-if="dateType !== 'date'">
                    <div class="item flex items-center justify-center fixed-width border-right" :class="getFixWidth()" v-for="(haltingCauses, causeIndex) in item.haltingCauses" :key="`causeIndex${causeIndex}`">
                      <div>
                        {{haltingCauses.causeName}}
                        <q-tooltip>{{haltingCauses.causeName}}</q-tooltip>
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <div v-for="(shift, shiftIndex) in item.shifts" :key="`shiftIndex${shiftIndex}`">
                      <div class="item border-bottom border-right">{{shift.shiftName}}</div>
                      <div class="flex nowrap">
                        <div class="item fixed-width border-right" :class="getFixWidth()" v-for="(haltingCauses, causeIndex) in shift.haltingCauses" :key="`causeIndex${causeIndex}`">
                          <div>
                            {{haltingCauses.causeName}}
                            <q-tooltip>{{haltingCauses.causeName}}</q-tooltip>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                  <div class="item flex items-center justify-center fixed-width border-right" :class="getFixWidth()">合计</div>
                  <div class="item flex items-center justify-center border-right" :class="getFixWidth()">{{statusList[1].label}}占比</div>
                </div>
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <tr>
              <td>{{props.row.deviceName}}</td>
              <td v-for="(item, index) in props.row[`${dateType}s`]" :key="index" style="padding: 0">
                <div class="flex nowrap full-height">
                  <template v-if="dateType !== 'date'">
                    <div class="item fixed-width border-right full-height flex items-center justify-center" :class="getFixWidth()" v-for="(cause, causeIndex) in item.haltingCauses" :key="`${cause.causeId}${causeIndex}`"> {{ cause.haltingMinutes}}</div>
                  </template>
                  <template v-else v-for="(shift) in item.shifts">
                    <div class="item fixed-width border-right full-height flex items-center justify-center" :class="getFixWidth()" v-for="(cause, causeIndex) in shift.haltingCauses" :key="`${cause.causeId}${causeIndex}`"> {{ cause.haltingMinutes}}</div>
                  </template>
                  <div class="item flex items-center justify-center fixed-width border-right" :class="getFixWidth()">{{item.totalHaltingMinutes}}</div>
                  <div class="item flex items-center justify-center fixed-width border-right" :class="getFixWidth()">{{item.haltingProportion}}</div>
                </div>
              </td>
            </tr>
          </template>
        </q-table>
        <yz-pagination v-model="pagination" @onSearch="getStopReports(queryParams)"/>
      </div>
    </div>
    <stop-dialog
      ref="stopDialog"
      :rowData="rowData"
      :queryParams="rowParams"
      :stopType="stopType"
      @close="show=false"
      :show="show"
    ></stop-dialog>
    <basic-dialog :visible="showExcel"
                  title="导出EXCEL"
                  min-width="350px"
                  is-show-basic-footer
                  @close="showExcel=false"
                  @submit="submitDateExcel"
    >
      <div class="padding-20">
        <span class="font-16" style="margin-right: 6px">生产日期:</span>
        <date-picker format="YYYY-MM-DD"
                     :clearable="false"
                     :editable="false"
                     range
                     v-model="queryParams.excelDate"
                     placeholder="选择生产日期"
                     style="width: 220px"/>
      </div>
    </basic-dialog>
  </div>
</template>

<script>
import refreshMixin from '../../assets/js/refresh-mixin'
import publicFilter from './components/public-filter'
import CustomizedSwitch from 'src/components/customized-switch'
import { downloadStopExcel, getStopReports, getStopStatistics } from '../../boot/statistics/stop-reason'
import moment from 'moment'
import stopDialog from './components/stop-reason-dialog'
import GetPublicDate from './components/get-publice-date'
import STOPECHSRTD from './components/stop-echarts'
import _ from 'lodash'
import { mapActions, mapGetters } from 'vuex'
import { addListener } from 'resize-detector'
import echarts from 'echarts'
moment.locale('zh-cn')

export default {
  name: 'stop-reason',
  mixins: [refreshMixin],
  components: {
    publicFilter,
    stopDialog,
    CustomizedSwitch
  },
  data () {
    return {
      showScale: false, // 是否可以缩放
      chart: null,
      isRefresh: true,
      // 弹窗展示
      show: false,
      // 带过去的弹窗数据
      rowData: {},
      rowParams: {},
      // echarts后端请求的数据
      echartsData: {
        xValue: [],
        causeValue: [],
        percentage: []
      },
      // 原因类型
      causeType: {
        // 横向坐标值
        xValue: [],
        // 原因
        causeValue: [],
        // 百分比
        percentage: []
      },
      cause: {
        // 横向坐标值
        xValue: [],
        // 原因
        causeValue: [],
        // 百分比
        percentage: []
      },
      // 原因类别
      stopTypeOption: [
        {
          value: '1',
          label: '按原因类别查看'
        },
        {
          value: '2',
          label: '按原因查看'
        }
      ],
      stopType: '1',
      // 查询条件
      // 停机原因 日期 设备数量
      oprof_start: {
        date: '',
        num: '',
        count: ''
      },
      // 防止切换变换了dateType
      sumbitDate: '',
      columnsClone: [],
      tableData: [],
      tableDataClone: [],
      queryParams: {
        // 查询区条件
        dateRange: [
          moment(new Date())
            .subtract(6, 'days')
            .toDate(),
          new Date()
        ],
        dateData: [
          moment(
            moment(new Date())
              .subtract(6, 'days')
              .toDate()
          ).format('YYYY-MM-DD'),
          moment(new Date()).format('YYYY-MM-DD')
        ],
        excelDate: [],
        dateType: 'date',
        location: {
          id: ''
        }, // 所在位置
        devices: [],
        product: []
      },
      columns: [],
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      dateType: 'date',
      tableLoading: false,
      requestId: '',
      showExcel: false
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'client',
      'statusList'
    ])
  },
  watch: {
    echartsData: {
      handler (newPro) {
        this.getInitChart(newPro)
      },
      deep: true
    },
    showScale (val) {
      this.getInitChart(this.echartsData)
    }
  },
  methods: {
    getFixWidth () {
      if (this.columns.length === 1) {
        return 'fixed-width2'
      } else if (this.columns.length === 2) {
        return 'fixed-width1'
      }
      return 'fixed-width'
    },
    // echart 计算 y轴累计百分比
    getpercentageY (val) {
      const arr = []
      const sum = _.sum(val.map(v => Number(v))).toFixed(2)
      const deepValue = _.cloneDeep(val).map(v => Number(v))
      for (let i = 0; i < val.length; i++) {
        const member = _.sum(deepValue.slice(0, i + 1))
        arr[i] = ((member / sum) * 100).toFixed(2)
      }
      return arr
    },
    // 查询接口
    selfParams () {
      if (this.checkParams()) {
        this.getStopReports(this.queryParams)
        // 获取表格数据
        this.getStopStatistics(this.queryParams)
        // 设置选中的dateType
        this.dateType = this.queryParams.dateType
      }
    },
    checkParams () {
      // 条件校验，日期不能超过7天，5周，12月
      if (this.queryParams.dateType === 'date' && Math.abs(moment(this.queryParams.dateRange[1]).diff(this.queryParams.dateRange[0], 'days')) >= 7) {
        this.$message.warning('日期范围不可超过7天')
        return
      }
      if (this.queryParams.dateType === 'week' && Math.abs(moment(this.queryParams.dateRange[1]).diff(this.queryParams.dateRange[0], 'weeks')) >= 5) {
        this.$message.warning('日期范围不可超过5周')
        return
      }
      if (this.queryParams.dateType === 'month' && Math.abs(moment(this.queryParams.dateRange[1]).diff(this.queryParams.dateRange[0], 'months')) >= 12) {
        this.$message.warning('日期范围不可超过12月')
        return
      }

      const getPublicDate = new GetPublicDate(
        this.queryParams.dateRange,
        this.queryParams.dateType
      )
      switch (this.queryParams.dateType) {
        case 'date':
          this.queryParams.dateData = getPublicDate._setDay()
          this.queryParams._getTableHeader = getPublicDate._getTableHeaderDay()
          break
        case 'week':
          this.queryParams.dateData = getPublicDate._setWeek()
          this.queryParams._getTableHeader = getPublicDate._getTableHeaderWeek(
            this.queryParams
          )
          break
        case 'month':
          this.queryParams.dateData = getPublicDate._setYear()
          this.queryParams._getTableHeader = getPublicDate._getTableHeaderMonth(
            this.queryParams
          )
          break
      }
      // 显示日期设备上
      this.oprof_start.date = getPublicDate._setReasonDate().join('~')
      // 由自组件传来数据动态设置table表头
      this.columnsClone = this.queryParams._getTableHeader

      return true
    },
    // 切换原因,进行改变E charts显示数据
    onChangeStopType (val) {
      if (val === '1') {
        this.echartsData = this.causeType
      } else {
        this.echartsData = this.cause
      }
    },
    // 初始化Echarts表格
    getInitChart (data) {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.dialogChart)
      }
      this.chart.setOption(
        new STOPECHSRTD({ ...data, id: '时间(分钟)', isDisabled: this.showScale }).option
      )
    },
    // 动态展示E chart
    setChartList () {
      // 原因类别
      Object.keys(this.causeType).map(v => {
        this.causeType[v] = []
      })
      this.tableDataClone[0].map(v => {
        this.causeType.xValue.push(v.causeGroupName)
        this.causeType.causeValue.push(Number(v.seconds))
      })
      this.causeType.percentage = this.getpercentageY(this.causeType.causeValue)
      // 原因查看
      Object.keys(this.cause).map(v => {
        this.cause[v] = []
      })
      this.tableDataClone[1].map(v => {
        this.cause.xValue.push(v.causeName)
        this.cause.causeValue.push(Number(v.seconds))
      })
      this.cause.percentage = this.getpercentageY(this.cause.causeValue)
      // 1===>类别 2===原因
      this.echartsData = Object.assign(
        {},
        this.stopType === '1' ? this.causeType : this.cause
      )
    },
    // 合计展示
    showDialog (val) {
      this.rowData = val
      this.rowParams = _.cloneDeep(this.queryParams)
      this.rowParams.dateType = this.sumbitDate
      this.show = true
    },
    downloadExcel () {
      if (_.isEmpty(this.queryParams.dateRange)) {
        return this.$q
          .dialog({
            title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>请选择日期范围</p>`,
            html: true,
            ok: {
              unelevated: true,
              label: '确认'
            }
          })
      }
      this.checkParams()
      if (this.queryParams.dateType === 'date') {
        this.queryParams.excelDate = this.queryParams.dateRange
        this.showExcel = true
      } else {
        this.download()
      }
    },
    submitDateExcel () {
      if (Math.abs(moment(this.queryParams.excelDate[1]).diff(this.queryParams.excelDate[0], 'days')) >= 31) {
        this.$message.warning('日期范围不可超过31天')
        return
      }
      this.download()
    },
    // 导出xls
    download () {
      const val = this.queryParams
      console.log(val)
      const data = {
        deviceIds: val.devices[0] === 'all' ? [] : val.devices,
        startDate: this.queryParams.dateType === 'date' ? moment(this.queryParams.excelDate[0]).format('YYYY-MM-DD') : val.dateData[0],
        endDate: this.queryParams.dateType === 'date' ? moment(this.queryParams.excelDate[1]).format('YYYY-MM-DD') : val.dateData[1],
        schemeLevel: val.location.level,
        schemeLevelId: val.location.id,
        dateType: val.dateType,
        workshopName: val.workshopName
      }
      const params = [{ name: '' }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      data['requestId'] = res.fileNameNew
      this.onSubscribe()
      downloadStopExcel(data).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        } else if (this.queryParams.dateType === 'date') {
          this.showExcel = false
        }
      }).catch(() => {
        this.closeUbscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      await this.$saveFileForBlob(msg.data, `${this.getData(this.queryParams.dateRange[0])}-${this.getData(this.queryParams.dateRange[1])}${this.statusList[1].label}原因报表.xls`)
      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },
    getData (data) {
      return moment(data).format('YYYYMMDD')
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    },
    setOprofNum (val) {
      this.$set(this.oprof_start, 'count', val)
      this.$set(this.oprof_start, 'num', val)
    },
    // 初始化查询接口
    getStopReports (val) {
      const params = {
        deviceIds: val.devices[0] === 'all' ? [] : val.devices,
        startDate: val.dateData[0],
        endDate: val.dateData[1],
        schemeLevel: val.location.level,
        schemeLevelId: val.location.id,
        dateType: val.dateType,
        pageSize: this.pagination.pageSize,
        pageNum: this.pagination.pageNum
      }
      this.sumbitDate = val.dateType
      this.oprof_start.num = val.devices[0] === 'all' ? this.oprof_start.count : val.devices.length
      this.tableLoading = true
      getStopReports(params).then(res => {
        this.tableData = res.data.list
        this.pagination.rowsNumber = res.data.total
        if (this.tableData.length > 0) {
          this.columns = this.tableData[0]?.dates || this.tableData[0]?.weeks || this.tableData[0]?.months || []
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    getStopStatistics (val) {
      const params = {
        deviceIds: val.devices[0] === 'all' ? [] : val.devices,
        startDate: val.dateData[0],
        endDate: val.dateData[1],
        schemeLevel: val.location.level,
        schemeLevelId: val.location.id,
        dateType: val.dateType,
        pageSize: this.pagination.pageSize,
        pageNum: this.pagination.pageNum
      }
      this.chart && this.chart.showLoading()
      getStopStatistics(params).then(res => {
        const ret = res.data
        this.tableDataClone = [
          this.setCauseGroup(ret),
          this.setCause(ret)
        ]
        this.setChartList()
      }).finally(() => {
        this.chart && this.chart.hideLoading()
      })
    },
    // return 类型arr
    // 原因类型查看 dailyReports ===> reports 后期要换
    setCauseGroup (val) {
      const p = _.cloneDeep(val)
      const arr = _.uniqBy(p, 'causeGroupId')
      p.forEach(v => {
        arr.forEach(j => {
          if (v.causeGroupId === j.causeGroupId && v.causeId !== j.causeId) {
            j.seconds = new this.$Big(j.seconds).plus(v.seconds).toFixed(0)
          }
        })
      })
      arr.forEach((item, index) => {
        item.seconds = new this.$Big(item.seconds / 60).toFixed(1)
        item.indexId = index + 1
      })
      return arr.sort((a, b) => b.seconds - a.seconds)
    },
    // return 原因arr
    setCause (val) {
      const p = _.cloneDeep(val)
      p.forEach((item, index) => {
        item.causeName = item.causeGroupName + '/' + item.causeName
        item.seconds = new this.$Big(item.seconds / 60).toFixed(1)
        item.indexId = index + 1
      })
      return p.sort((a, b) => b.seconds - a.seconds)
    },
    ...mapActions([
      'saveCustomerSet'
    ])
  },
  mounted () {
    this.saveCustomerSet()
    addListener(this.$refs.dialogChart, this.$utils.debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100))
  }
}
</script>
<style scoped lang='stylus'>
>>> .q-table__middle{
  border-bottom 1px solid #d3d3d3
}
.stop-reason {
  >>>.borderless .q-field__ {
    &control, &append {
      height: 21px;
      min-height: 21px;
      padding-left: 5px;
    }

    &control-container {
      line-height: 21px;
      padding: 0;
    }

    &native {
      padding: 0;
    }
  }

  >>>.q-field__marginal {
    font-size: 16px;
    color: black;
    font-weight: 400;
    text-align: right;
  }

  .scroll-box {
    overflow-y: scroll;

    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
      background-color: rgba(95, 119, 253, 0);
      transition: all 0.3s;

      &-thumb {
        border-radius: 6px;
        background-color: rgba(95, 119, 253, 0);
        transition: all 0.3s;
      }

      &-track {
        margin-left: -6px;
        padding-top: 48px;
        background-color: transparent;
        width: 0;
      }
    }

    &:hover::-webkit-scrollbar-thumb {
      background-color: rgba(95, 119, 253, 0.5);
    }
  }
}

.item {
  padding: 0 10px;
  line-height: 2;
  text-align: center;
  div {
    overflow: hidden;
  }
}
.border-bottom {
  border-bottom: 1px solid #d3d3d3;
}
.border-right {
  border-right: 1px solid #d3d3d3;
}
.fixed-width {
  width: 112px;
}
.fixed-width1 {
  width: 200px;
}
.fixed-width2 {
  width: 320px;
}
.nowrap{
  flex-wrap: nowrap;
}
.my-sticky-header-table
  height: 630px

  thead tr th
    position: sticky
    z-index: 10
  thead tr:first-child th
    top: 0
  thead tr:first-child th:first-child
    z-index: 11
  &.q-table--loading thead tr:last-child th
    top: 48px
</style>
